package me.zingon.WebSocket.ws;

import me.zingon.WebSocket.tools.TalkService;
import me.zingon.WebSocket.tools.TankService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.*;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;
import org.springframework.web.util.HtmlUtils;

/**
 * Created by ZTC on 12/20/2016.
 */
@Component
public class TalkWS extends AbstractWebSocketHandler {

    @Autowired
    TalkService talkService;

    @Autowired
    TankService tankService;

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        String[] params=session.getUri().getQuery().split("=");
        //p[0]:name ; p[1]:reqId
        String[] p=params[1].split("_");
        if(p[0].length()>5)
            p[0]=params[0].substring(0,5);
        session.getAttributes().put("reqId",p[1]);
        talkService.saveTalker(p[0],p[1],session);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String msg=message.getPayload();
        String reqId= (String) session.getAttributes().get("reqId");
        if(msg.contains("action"))
            tankService.doAction(msg,reqId);
        else if(msg.equals("resA"))
            tankService.resA(reqId);
        else if(msg.equals("resB"))
            tankService.resB(reqId);
        else {
            String sendMsg=msg.trim();
            if(msg.length()>50) {
                sendMsg = msg.trim().substring(0, 50);
            }
            talkService
                    .send2All("{\"talkMsg\":\""+HtmlUtils.htmlEscape(sendMsg)+"\"}");
        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        talkService.rmTalker((String) session.getAttributes().get("reqId"));
        System.out.println((String) session.getAttributes().get("reqId")+" talkws_closing..");
    }
}
